<template>
  <template v-if="getShow">
    <LoginFormTitle class="enter-x" />
    <a-form layout="vertical" ref="formRef" class="enter-x p-4" name="basic" :model="formData" @finish="onFinish">
      <a-form-item label="钉钉手机号" class="enter-x" name="phone" 
        :rules="[
          {
            required: true,
            validator: (_, value) => validatePhoneNumber(value),
            trigger: ['change', 'blur']
          }
        ]"
        >
        <a-input
          class="input-phone"
          v-model:value="formData.phone" 
          size="large" 
          placeholder="请输入你的钉钉手机号" />
      </a-form-item>
      <a-form-item class="enter-x" name="verifyCode" :rules="[{ required: true, message: '请输入钉钉验证码' }]">
        <a-input-group compact>
          <a-input
            class="input-phone"
            v-model:value="formData.verifyCode" 
            size="large"
            style="width: calc(100% - 143px)"
            placeholder="请输入验证码" />
            <a-button v-show="show" type="primary" size="large" class="input-phone btn-code" @click="verification">获取钉钉验证码</a-button>
            <a-button v-show="!show" disabled type="primary" size="large" class="input-phone btn-code w-143px">{{ count }} s 后获取</a-button>
          </a-input-group>
      </a-form-item>
      <a-form-item>
        <a-button html-type="submit" class="mt-15px h-40px!" type="primary" block :loading="loading">
          确定
        </a-button>
        <div class="text-center mt-40px color-#209EE4 font-size-15px cursor-pointer" @click="handleBackLogin">
          <arrow-left-outlined class="mr-5px font-size-15px"/> 返回登录
        </div>
      </a-form-item>
    </a-form>
  </template>
  <template v-if="getShowLast">
    <LoginFormTitle class="enter-x" />
    <a-form :rules="rules" layout="vertical" ref="formRefv" class="enter-x p-4" name="basic" :model="formDatav" @finish="onFinishv">
      <a-form-item class="enter-x" label="新密码" name="newPassword">
        <a-input-password
          v-model:value="formDatav.newPassword"
          placeholder="请输入密码"
          size="large" 
          name="password" 
          autocomplete="new-password"
        />
        <div class="tips">包含6-12个字符、数字、字母</div>
      </a-form-item>
      <a-form-item class="enter-x" label="确认密码" name="virtuallyPassword">
        <a-input-password
          v-model:value="formDatav.virtuallyPassword"
          placeholder="请输入密码"
          size="large" 
        />
      </a-form-item>
      <a-form-item>
        <a-button html-type="submit" class="mt-15px h-40px!" type="primary"  block :loading="loadingv">
          确定
        </a-button>
        <div class="text-center mt-40px color-#209EE4 font-size-15px cursor-pointer" @click="handleBackLogin">
          <arrow-left-outlined class="mr-5px font-size-15px"/> 返回登录
        </div>
      </a-form-item>
    </a-form>
  </template>
</template>

<script lang="ts" setup>
import { computed, reactive, ref, unref } from 'vue'
import LoginFormTitle from './LoginFormTitle.vue'
import { LoginStateEnum, useLoginState } from './useLogin'
import { message } from 'ant-design-vue';
import { getDingTalkVerification, verifyCode } from '@/api/applay/login/login'
import type { Rule } from 'ant-design-vue/es/form'
import { resetPassword } from '@/api/applay/login/login'

const { handleBackLogin, getLoginState, setLoginState } = useLoginState()

const formRef = ref()
const loading = ref(false)
const formData = reactive({
  phone: '', // 钉钉手机号
  verifyCode: '', // 验证码
})

const formRefv = ref()
const loadingv = ref(false)
const formDatav = reactive({
  newPassword: '',
  virtuallyPassword: '',
})

const getShow = computed(() => unref(getLoginState) === LoginStateEnum.RESET_PASSWORD)
const getShowLast = computed(() => unref(getLoginState) === LoginStateEnum.UPDATE)

// 校验规则
let validatePass = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject('请输入密码')
  } else {
    // @ts-ignore
    if(_rule.field == 'newPassword'){
      let regex = /^(?=.*[0-9])(?=.*[a-zA-Z])[0-9a-zA-Z]{6,12}$/
      if(!regex.test(value)){
        return Promise.reject('格式错误')
      } 
      // @ts-ignore
    }else if(_rule.field == 'virtuallyPassword'){
      if(value != formDatav.newPassword){
        return Promise.reject('两次密码不一致')
      }
    }
    return Promise.resolve();
  }
}

// rules集合
const rules: Record<string, Rule[]> = {
  newPassword: [{ required: true, validator: validatePass, trigger: 'change' }],
  virtuallyPassword: [{ required: true, validator: validatePass, trigger: 'change' }],
}

// 验证手机号的方法
function validatePhoneNumber(phoneNumber) {
  // 假设中国大陆手机号码格式
  const regex = /^1[3-9]\d{9}$/;
  if (regex.test(phoneNumber)) {
    return Promise.resolve('成功')
  } else {
    return Promise.reject('请输入有效钉钉手机号');
  }
}

// 发送验证码
const TIME_COUNT = ref(60)
const timer = ref()
const count = ref()
const show = ref(true)
async function verification(){
  const is = await validatePhoneNumber(formData.phone)
  if(is !== '成功'){
    message.error('请输入有效钉钉手机号')
    return
  }
  if (!timer.value) {
    let params = {
      phone: formData.phone,
    }
    const res = await getDingTalkVerification(params)
    if(res.code == 10000){
      message.success("验证码发送成功")
      count.value = TIME_COUNT.value
      show.value = false
      timer.value = setInterval(() => {
        if (count.value > 0 && count.value <= TIME_COUNT.value) {
          count.value--
        } else {
          show.value = true
          clearInterval(timer.value);
          timer.value = null
        }
      }, 1000)
    }else{
      message.error(res.msg)
    }
  }
}

// 确定
async function onFinish(values) {
  loading.value = true
  let params = {
    phone: formData.phone,
    verifyCode: formData.verifyCode,
  }
  const res = await verifyCode(params).finally(()=> loading.value = false)
  if(res.code == 10000){
    message.success("验证成功")
    setLoginState(LoginStateEnum.UPDATE)
  }else{
    message.error(res.msg)
  }
}

// 修改密码
async function onFinishv() {
  loadingv.value = true
  let params = {
    phone: formData.phone,
    newPassword: formDatav.newPassword,
  }
  const res = await resetPassword(params).finally(()=> loadingv.value = false)
  if(res?.code && res.code != '10000'){
    message.error(res.msg)
  }else{
    message.success("修改成功")
    handleBackLogin()
  }
}
</script>

<style lang="less" scoped>
.enter-x{
  color:#333;
  .input-phone{
    margin-top: 6px;
  }
  .btn-code{
    border-top-left-radius: 0px;
    border-bottom-left-radius: 0px;
  }
  .tips{
    height: 20px;
    margin-top: 15px;
    font-weight: 400;
    font-size: 14px;
    color: #B3C0C8;
    line-height: 16px;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }
}
</style>